const router = require('koa-router')()
const Mock = require('mockjs')

const { list } = Mock.mock({
  "list|50": [{
    "id": "@id",
    "name": "@cname",
    "tel": /1[3-9]\d{9}/
  }]
})

router.get('/list', ctx => {
  const { q = '' } = ctx.request.query
  ctx.body = list.filter(v => JSON.stringify(v).includes(q))
})

router.delete('/list/:id', ctx => {
  const { id } = ctx.params;
  const index = list.findIndex(v => v.id === id);
  list.splice(index, 1);
  ctx.body = '删除成功'
})


router.post('/list/', ctx => {
  list.push({
    ...ctx.request.body,
    id: Mock.mock('@id'),
  })
  ctx.body = '添加成功'
})


router.put('/list/:id', ctx => {
  const { id } = ctx.params;
  const item = list.find(v => v.id === id);
  Object.assign(item, ctx.request.body);
  ctx.body = '修改成功'
})

module.exports = router
